package com.asset.salesforce.dao;



import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.asset.salesforce.domain.Role;
import com.asset.salesforce.domain.User;


@Repository
public class RoleShiroDaoImpl {
	

	@Autowired
	private SessionFactory sessionFactory;
	
	public void editRole(Role role){
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(role);
	}
	
	public void addRole(Role role) {
		try{
		sessionFactory.getCurrentSession().save(role);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void deleteRole(Role role) {
		try{
		sessionFactory.getCurrentSession().delete(role);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public List<Role> getAllRoles() {
		try{
		Query query =sessionFactory.getCurrentSession().createQuery("from Role");
		return  query.list();
		
		
		}catch(Exception ex){
			ex.printStackTrace();
			return null;
		}
	}
	
	public Role getRoleById(Integer roleId) {
        return (Role) sessionFactory.getCurrentSession().load(Role.class, roleId);
    }
	
	
	public Role findRole(String name) {
	    Session session = sessionFactory.getCurrentSession();
	    
        String query = "from Role r where r.name = :name";
        Query query2 = session.createQuery(query);
        query2.setParameter("name", name);
        List<Role> roles =new ArrayList<Role>();
        roles = query2.list();
        if(roles != null &&roles.size() >0){
        	return roles.get(0);
         }else{
        	 return new Role("");
         }
        
    }
	
	public Long countRole() {
		return (Long) sessionFactory.getCurrentSession().createQuery("select count(r.id) from Role r").uniqueResult();
	}

}
